package com.itheima.controller.admin;


import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.POIUtils;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrdersettingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping ("/ordersetting")
@RestController
@Api (tags = "预约设置")
public class OrdersettingController {
    @Autowired
    private OrdersettingService ordersettingService;
    /**
     * 文件上传
     *
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result upload(@RequestParam("excelFile")  MultipartFile excelFile) {
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);//解析表格数据
            List<OrderSetting> data=new ArrayList<>();//封装到OrderSetting对象中
            for (String[] strings : list) {
                //封装数据
                OrderSetting orderSetting = new OrderSetting(new Date(strings[0]), Integer.parseInt(strings[1]));
                //添加到集合中
                data.add(orderSetting);
            }
            //调用业务层方法，完成预约设置
            ordersettingService.add(data);

            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }


    /**
     * 模板下载接口
     */
    @GetMapping("/download")
    public void downloadTemplate(@RequestParam("filename") String filename, HttpServletResponse response) throws Exception {
        // 1. 校验文件名是否为空
        if (!StringUtils.hasText(filename)) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        // 2. 构建完整文件路径（可以根据实际情况配置）
        File file = new File("D:\\templates\\" + filename);

        if (!file.exists()) {
            throw new RuntimeException("文件不存在，请检查路径或文件名");
        }

        // 3. 设置响应头，告诉浏览器这是一个附件下载
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

        // 4. 创建输入流和输出流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    /**
     * 根据年月查询对应的预约设置信息
     *
     */
    @GetMapping("/getOrderSettingByMonth")
    @ApiOperation("根据年月查询对应的预约设置信息")
    public Result getOrderSettingByMonth(@RequestParam("month") String month) {
        try {
            // 调用业务层方法，根据传入的日期字符串查询预约设置信息
            List<Map> list = ordersettingService.getOrderSettingByMonth(month);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }
    /**
     * 根据日期修改可预约人数
     *
     */
    @PostMapping("/editNumberByOrderDate")
    @ApiOperation("根据日期修改可预约人数")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting) {
        try {
            ordersettingService.editNumberByOrderDate(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }



}
